package com.iepacj.concurrency.ch4.one;

import java.util.concurrent.TimeUnit;

public class Interrupted {

    public static void main(String[] args) throws InterruptedException {

        Thread sleepThread = new Thread(new SleepRunner(), "SleepThread");
        sleepThread.setDaemon(true);

        Thread busyThread = new Thread(new BusyRunner(), "BusyThread");
        busyThread.setDaemon(true);

        sleepThread.start();
        busyThread.start();

        // 休眠5秒  让两个线程充分运行
        TimeUnit.SECONDS.sleep(5);

        // 中断相当于线程的一个标志位
        // 表示一个运行中的线程, 是否被其他线程执行了中断操作
        // 其他线程通过调用线程的interrupt方法
        // 对线程进行中断操作
        sleepThread.interrupt();

        busyThread.interrupt();

        System.out.println("SleepThread interrupted is " + sleepThread.isInterrupted());

        System.out.println("BusyThread interrupted is " + busyThread.isInterrupted());

        // 防止两个线程立刻退出
        SleepUtils.second(30);

        busyThread.interrupted();
        System.out.println("BusyThread interrupted is " + busyThread.isInterrupted());

        SleepUtils.second(3);
        System.out.println("程序退出");

        /*
         * 这种通过标志位或者中断的方式能够使线程在终止时能够使线程有机会
         * 清理一些资源, 而不是武断的去停止, 这种终止线程的方式更加安全和优雅
         */

    }


    static class SleepRunner implements Runnable {

        @Override
        public void run() {
            while (true) {
                SleepUtils.second(3);
            }
        }
    }

    static class BusyRunner implements Runnable {

        @Override
        public void run() {
            while (true) {
               //System.out.println("ddd ");
            }
        }
    }

}
